import matplotlib.pyplot as plt
import csv
from datetime import datetime
from pathlib import Path

# 读取文件
path = Path('death_valley_2021_simple.csv')
lines = path.read_text().splitlines()
reader = csv.reader(lines)
header_row = next(reader)

# 获取所需信息的索引
high_index = header_row.index('TMAX')
date_index = header_row.index('DATE')
low_index = header_row.index('TMIN')
name_index = header_row.index('NAME')

# 获取数据
dates,highs,lows = [],[],[]
place_name = ''
for row in reader:
    # 若地名为空
    if not place_name:
        place_name = row[name_index]
    current_data = datetime.strptime(row[date_index],"%Y-%m-%d")
    try:
        high = int(row[high_index])
        low = int(row[low_index])
    except ValueError:
        print(f"Missing data for {current_data}")
    else:
        dates.append(current_data)
        highs.append(high)
        lows.append(low)

# 根据气温数据绘图
plt.style.use('seaborn-v0_8')
fig,ax = plt.subplots()
ax.plot(dates,highs,color='red',alpha=0.5)
ax.plot(dates,lows,color='blue',alpha=0.5)
ax.fill_between(dates,highs,lows,alpha=0.1)

# 设置图像格式
title = "Daily high and low temperature in "+ place_name
ax.set_title(title,fontsize=14)
ax.set_xlabel('',fontsize=14)
fig.autofmt_xdate()
ax.set_ylabel("Temperature(F)",fontsize=14)
ax.tick_params(labelsize=16)

plt.show()